<template>
  <PageWrapper dense>
    <a-row>
      <a-col :xl="8" :sm="24">
        <SysDictTypeList @change="handleDictTypeChange" />
      </a-col>
      <a-col :xl="16" :sm="24">
        <!-- 表格 -->
        <BasicTable
          @register="registerTable"
          :searchInfo="searchInfo"
          :rowSelection="{ type: 'checkbox', onChange: onSelectChange }"
        >
          <template #toolbar>
            <Authority value="sys:dict:save">
              <a-button-add @click="handleCreate" />
              <a-button-import import-code="sys:dict" />
            </Authority>
            <a-button-export
              :loading="exportBtnLoading"
              auth="sys:dict:select"
              @click="handelExportData"
            />
            <a-button-remove-batch
              auth="sys:dict:remove"
              :id="checkedKeys"
              :api="remove"
              @success="reload"
            />
            <Authority value="sys:dict:save">
              <a-button @click="reloadCache">
                <Icon icon="ant-design:reload-outlined" />
                刷新缓存
              </a-button>
            </Authority>
          </template>

          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
              <a-tag v-if="record.color" :color="record.color" :bordered="false">{{
                record.name
              }}</a-tag>
              <span v-else>{{ record.name }}</span>
            </template>
            <template v-if="column.key === 'action'">
              <div class="basic-table-action center">
                <a-button-add-sub
                  auth="sys:dict:save"
                  small
                  @click="handleCreate(record.id, record.dictType)"
                />
                <a-divider type="vertical" />
                <a-button-edit small auth="sys:dict:save" :id="record.id" @click="handleEdit" />
                <a-divider type="vertical" />
                <a-button-remove
                  small
                  auth="sys:dict:remove"
                  :id="record.id"
                  :api="remove"
                  @success="reload"
                />
              </div>
            </template>
          </template>
        </BasicTable>
      </a-col>
    </a-row>
    <!-- 表单 -->
    <SysDictInput @register="registerDrawer" @success="reload" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, nextTick, reactive, ref } from 'vue';
  import { BasicTable, useTable } from '@/components/Table';
  import { select, add, get, remove, refresh, exportData } from '@/api/sys/sysDict';
  import { columns } from '@/views/sys/dict/dict.data';
  import { useDrawer } from '@/components/Drawer';
  import {
    AButtonAdd,
    AButtonEdit,
    AButtonRemove,
    AButtonRemoveBatch,
    AButtonImport,
    AButtonExport,
  } from '@/components/Button';
  import SysDictInput from '@/views/sys/dict/Input.vue';
  import { Icon } from '@/components/Icon';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useDictStore } from '@/store/modules/dict';
  import { Authority } from '@/components/Authority';
  import { PageWrapper } from '@/components/Page';
  import SysDictTypeList from '@/views/sys/dict/type/List.vue';
  import { downloadFileById } from '@/utils/file/download';
  import { SysDict } from '@/api/sys/model/sysDictModel';
  import AButtonAddSub from '@/components/Button/src/ButtonAddSub.vue';

  export default defineComponent({
    name: 'SysDictList',
    components: {
      AButtonAddSub,
      AButtonExport,
      AButtonImport,
      SysDictTypeList,
      PageWrapper,
      Authority,
      Icon,
      SysDictInput,
      AButtonRemoveBatch,
      AButtonRemove,
      AButtonEdit,
      AButtonAdd,
      BasicTable,
    },
    setup() {
      const { createMessage } = useMessage();
      // 导出按钮状态
      const exportBtnLoading = ref<boolean>(false);
      // 表格选中数据
      const checkedKeys = ref<Array<string>>([]);
      const searchInfo = reactive<Recordable>({
        dictType: '',
      });
      const [registerDrawer, { openDrawer }] = useDrawer();
      /**
       * 初始化表格
       */
      const [registerTable, { reload, getForm }] = useTable({
        title: '字典',
        api: select,
        columns,
        useSearchForm: true,
        formConfig: {
          schemas: [
            {
              field: 'code',
              label: '字典编码',
              component: 'Input',
            },
            {
              field: 'name',
              label: '字典名称',
              component: 'Input',
            },
          ],
        },
        actionColumn: {
          width: 280,
          title: '操作',
          key: 'action',
        },
      });

      function handleDictTypeChange(dictTypeId: string | null, dictType: string | null) {
        console.log(dictType);
        searchInfo.dictType = dictType;
        reload();
      }

      /**
       * 新增
       *
       * @param id 上级id
       * @param dictType 字典类型
       */
      const handleCreate = (id: string | undefined, dictType: string | undefined) => {
        if (!dictType) {
          dictType = searchInfo.dictType;
        }

        add(id, dictType).then((data) => {
          openDrawer(true, data);
        });
      };

      function handleEdit(id: string) {
        get(id).then((data) => {
          openDrawer(true, data);
        });
      }

      const reloadTable = () => {
        nextTick(() => {
          reload();
        });
      };

      /**
       * 刷新redis缓存和本地缓存
       */
      const reloadCache = () => {
        refresh().then(() => {
          const dictStore = useDictStore();
          dictStore.initDict(true, () => {
            createMessage.success('刷新成功');
            reloadTable();
          });
        });
      };

      const handelExportData = async () => {
        exportBtnLoading.value = true;
        try {
          await exportData(Object.assign(searchInfo, getForm().getFieldsValue()) as SysDict).then(
            (id) => {
              downloadFileById(id);
            },
          );
        } catch (e) {
          console.error('导出数据错误', e);
        } finally {
          exportBtnLoading.value = false;
        }
      };

      return {
        searchInfo,
        checkedKeys,
        exportBtnLoading,
        onSelectChange(selectedRowKeys: string[]) {
          checkedKeys.value = selectedRowKeys;
        },
        remove,
        handleDictTypeChange,
        registerDrawer,
        registerTable,
        reload,
        handleCreate,
        handleEdit,
        reloadCache,
        handelExportData,
      };
    },
  });
</script>
